package com.twu.biblioteca.Domain;

import com.twu.biblioteca.Entity.User;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by hjli on 7/27/14.
 */
public class UserService{

    private List<User> userList;

    public User getCurrentUser() {
        return currentUser;
    }

    public void setCurrentUser(User currentUser) {
        this.currentUser = currentUser;
    }

    private User currentUser;

    public UserService() {
        userList = new ArrayList<User>();
        User user_one = new User("111-1111","zhang san","1","1@gmail.com","Hubei China","0271111111","librarian");
        User user_two= new User("222-2222","li si","2","2@gmail.com","Sichuan China","0281111111","customer");
        User user_three = new User("333-3333","wang wu","3","3@gmail.com","ShangHai China","0211111111","customer");
        User user_four = new User("444-4444","zhao liu","4","4@gmail.com","Hubei China","02722222222","customer");

        userList.add(user_one);
        userList.add(user_two);
        userList.add(user_three);
        userList.add(user_four);
        currentUser = null;
    }

    public String logIn(String libraryNumber, String password) throws Exception {
        String result = null;
        User userToLog = getUserByLibraryNumber(libraryNumber);
        if(userToLog != null){
            if(isUserLibraryNumberMatchPassword(userToLog,password)){
                currentUser = userToLog;
                result = "Success";
            }
            else{
                currentUser = null;
                result = "libraryNumber is not match with password";
            }
        }
        else{
            currentUser = null;
            result = "can't find the the user";
        }
        return result;
    }


    public User getUserByLibraryNumber(String libraryNumber){
        User userToReturn = null;
        Iterator<User> iter = userList.iterator();
        while(iter.hasNext()){
            User user = (User)iter.next();
            if(user.getLibraryNumber().equals(libraryNumber)){
                userToReturn = user;
                break;
            }
        }
        return  userToReturn;
    }

    public boolean isUserLibraryNumberMatchPassword(User userToLog, String password){
        if(userToLog.getPassword().equals(password)){
            return true;
        }
        else{
            return false;
        }
    }

    public String showPersonalInfo(){
        return currentUser.toString();
    }
}
